import axios from "axios"
import { message } from "antd"
import {getToken} from '../utils/user-token'

// 定义响应数据类型
export type ResType ={
  code:number,
  data?:ResDataType,
  msg?:string
}
export type ResDataType = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key:string]:any
}

// 创建 Axios 实例
const service = axios.create({
  baseURL: '/api',
  timeout:10*1000,  // 设置超时时间为 10 秒
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer${getToken()}`
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截器：统一处理code和msg
service.interceptors.response.use((res) => {
  const resData = (res.data || {}) as ResType
  const {code,data,msg} = resData
  // 错误提示
  if(code !== 200){
    if(msg){
      message.error(msg)
    }
    throw new Error('请求失败')
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  return data as any
})

export default service